package com.ruoyi.web.controller.system;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Act;
import com.ruoyi.system.dto.ActStatSearchDTO;
import com.ruoyi.system.service.IActService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.vo.ActStatVO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ActStat;
import com.ruoyi.system.service.IActStatService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 作品统计Controller
 *
 * @author xuyk
 * @date 2022-01-03
 */
@Controller
@RequestMapping("/system/stat")
public class ActStatController extends BaseController
{
    private String prefix = "system/stat";

    @Autowired
    private IActStatService actStatService;

    @Autowired
    private IActService actService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Value("${ruoyi.statExportName:作品统计数据}")
    private String statExportName;

    @RequiresPermissions("system:stat:view")
    @GetMapping()
    public String stat(ModelMap mmap)
    {
        boolean canOperation = getUserOperationPower();
        if(!canOperation){
            SysDept dept = sysDeptService.selectDeptById(getSysUser().getDeptId());
            if(dept == null){
                return null;
            }
            if(dept.getAncestors().startsWith("0,100") || dept.getDeptId().intValue() == 100){
                canOperation = true;
            }
        }
        mmap.put("canOperation",canOperation);
        return prefix + "/stat";
    }

    /**
     * 查询作品统计列表
     */
    @RequiresPermissions("system:stat:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ActStatSearchDTO searchDTO)
    {
        searchDTO.setCurUser(getSysUser());
        //获取当前用户所在院系
        SysDept school = sysDeptService.getUserSchools(searchDTO.getCurUser());
        if(school != null){
            searchDTO.setCurSchoolId(school.getDeptId());
        }
        SysDept faculty = sysDeptService.getUserFaculty(searchDTO.getCurUser());
        if(faculty != null){
            searchDTO.setCurFacultyId(faculty.getDeptId());
        }
        startPage();
        List<ActStatVO> list = actStatService.selectActStatByCondition(searchDTO);
        computeNum(list);
        return getDataTable(list);
    }

    private void computeNum(List<ActStatVO> list){
        //遍历查询数据
        if(list != null && list.size() > 0){
            for(ActStatVO actStatVO: list){
                computeNum(actStatVO);
            }
        }
    }

    private void computeNum(ActStatVO actStatVO) {
        String schoolName = actStatVO.getSchool();
        String beginChar = schoolName.substring(0,1);
        if("0123456789".indexOf(beginChar) > -1){
            String begin = schoolName.substring(0,6);
            begin = begin.replaceAll("[0-9|-]","");
            schoolName = begin + schoolName.substring(6);
        }
        actStatVO.setSchool(schoolName);

        List<Act> acts = actService.select4StatList(actStatVO);
        if(acts == null || acts.size() == 0){
            actStatVO.setZero();
            return;
        }

        Set<String> studentSet = new HashSet<String>();
        Set<String> teacherSet = new HashSet<String>();
        //计算
        for(Act act : acts){
            if(act.getCategoryId().intValue() == 1){
                actStatVO.setANum(actStatVO.getANum() + 1);
            }else if(act.getCategoryId().intValue() == 2){

            }else if(act.getCategoryId().intValue() == 3){
                actStatVO.setBaNum(actStatVO.getBaNum() + 1);
            }else if(act.getCategoryId().intValue() == 4){
                actStatVO.setBbNum(actStatVO.getBbNum() + 1);
            }else if(act.getCategoryId().intValue() == 5){
                actStatVO.setBcNum(actStatVO.getBcNum() + 1);
            }else if(act.getCategoryId().intValue() == 6){
                actStatVO.setCNum(actStatVO.getCNum() + 1);
            }else if(act.getCategoryId().intValue() == 7){
                actStatVO.setDNum(actStatVO.getDNum() + 1);
            }else if(act.getCategoryId().intValue() == 8){
                actStatVO.setENum(actStatVO.getENum() + 1);
            }else if(act.getCategoryId().intValue() == 9){
                actStatVO.setFNum(actStatVO.getFNum() + 1);
            }else if(act.getCategoryId().intValue() == 10){

            }else if(act.getCategoryId().intValue() == 11){
                actStatVO.setGaNum(actStatVO.getGaNum() + 1);
            }else if(act.getCategoryId().intValue() == 12){
                actStatVO.setGbNum(actStatVO.getGbNum() + 1);
            }else if(act.getCategoryId().intValue() == 13){
                actStatVO.setGcNum(actStatVO.getGcNum() + 1);
            }

            /*
            // 计算参赛学生数
            String students = act.getAuthor();
            if(StringUtils.isNotBlank(students)){
                students = students.trim()
                        .replace("、",",")
                        .replace("，",",")
                        .replace("，",",");
                String[] studentArr = students.split(",");
                if(studentArr != null && studentArr.length > 0){
                    for(int i = 0 ; i< studentArr.length; i++){
                        studentSet.add(studentArr[i].trim());
                    }
                }
            }

            //计算指导老师数量
            String teachers = act.getTeacher();
            if(StringUtils.isNotBlank(teachers) && !"无".equals(teachers)){
                teachers = teachers.trim()
                        .replace("、",",")
                        .replace("，",",")
                        .replace("，",",");
                String[] teacherArr = teachers.split(",");
                if(teacherArr != null && teacherArr.length > 0){
                    for(int i = 0 ; i< teacherArr.length; i++){
                        teacherSet.add(teacherArr[i].trim());
                    }
                }
            }

             */
        }

        //actStatVO.setStudentNum((long) studentSet.size());
        //actStatVO.setTeacherNum((long) teacherSet.size());
        actStatVO.setValue();
    }

    /**
     * 导出作品统计列表
     */
    @RequiresPermissions("system:stat:export")
    @Log(title = "作品统计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ActStatSearchDTO searchDTO)
    {
        searchDTO.setCurUser(getSysUser());
        //获取当前用户所在院系
        SysDept school = sysDeptService.getUserSchools(searchDTO.getCurUser());
        if(school != null){
            searchDTO.setCurSchoolId(school.getDeptId());
        }
        SysDept faculty = sysDeptService.getUserFaculty(searchDTO.getCurUser());
        if(faculty != null){
            searchDTO.setCurFacultyId(faculty.getDeptId());
        }
        List<ActStatVO> list = actStatService.selectActStatByCondition(searchDTO);
        computeNum(list);
        ExcelUtil<ActStatVO> util = new ExcelUtil<ActStatVO>(ActStatVO.class);
        return util.exportExcel(list, this.statExportName);
    }

    /**
     * 新增作品统计
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存作品统计
     */
    @RequiresPermissions("system:stat:add")
    @Log(title = "作品统计", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ActStat actStat)
    {
        return toAjax(actStatService.insertActStat(actStat));
    }

    /**
     * 修改作品统计
     */
    @RequiresPermissions("system:stat:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        ActStat actStat = actStatService.selectActStatById(id);
        if(actStat != null){
            //修改学校名显示，去掉编号
            String schoolName = actStat.getSchool();
            String beginChar = schoolName.substring(0,1);
            if("0123456789".indexOf(beginChar) > -1){
                String begin = schoolName.substring(0,6);
                begin = begin.replaceAll("[0-9|-]","");
                schoolName = begin + schoolName.substring(6);
            }
            actStat.setSchool(schoolName);

            //计算教师和学生人数
            ActStatVO actStatVO = new ActStatVO();
            BeanUtils.copyProperties(actStat,actStatVO);
//            computeNum(actStatVO);
//            actStat.setStudentNum(actStatVO.getStudentNum());
//            actStat.setTeacherNum(actStatVO.getTeacherNum());
        }
        mmap.put("actStat", actStat);
        return prefix + "/edit";
    }

    /**
     * 修改保存作品统计
     */
    @RequiresPermissions("system:stat:edit")
    @Log(title = "作品统计", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ActStat actStat)
    {
        actStat.setCreateBy(getLoginName());
        actStat.setUpdateBy(getLoginName());
        return toAjax(actStatService.updateActStat(actStat));
    }

    /**
     * 删除作品统计
     */
    @RequiresPermissions("system:stat:remove")
    @Log(title = "作品统计", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(actStatService.deleteActStatByIds(ids));
    }


    @Autowired
    private ISysConfigService configService;

    private boolean getUserOperationPower(){
        String dateStr = configService.selectConfigByKey("game.end.time");
        if(StringUtils.isNotBlank(dateStr)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try{
                Date endTime = sdf.parse(dateStr);
                Date now = new Date();
                if(now.compareTo(endTime) >= 0){
                    return false;
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return  true;
    }
}
